﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Develop.DTO.DevelopProjectSales;
using AnQinFrameWorkAPI.Entity.Develop.Entity;
using AnQinFrameWorkAPI.Entity.Develop.View.DevelopProjectSales;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;
using static AnQinFrameWorkAPI.Common.Enum.DevelopEnum;

namespace AnQinFrameWorkAPI.Service.Develop;

/// <summary>
///     开发管理-项目销售业务层
/// </summary>
public class DevelopProjectSaleService
{
    //数据库
    private readonly DatabaseContext _context;

    //自动映射
    private readonly IMapper _mapper;

    //请求人信息
    private readonly IUserContext _userContext;

    //构造注入
    public DevelopProjectSaleService(IUserContext userContext, DatabaseContext context, IMapper mapper)
    {
        _userContext = userContext;
        _context = context;
        _mapper = mapper;
    }

    #region 获取开发管理项目销售列表

    public async Task<RequestResponseModel> GetProjectSale(DevelopProjectSalesSearchDTO developProjectSalesSearchDTO)
    {
        //获取筛选
        var query = _context.DevelopProjectManager
            .ProjectTo<DevelopProjectSalesView>(_mapper.ConfigurationProvider)
            .AsNoTracking()
            .WhereIF(
                a => a.ProjectCode.Contains(developProjectSalesSearchDTO.Project) ||
                     a.ProjectName.Contains(developProjectSalesSearchDTO.Project),
                !string.IsNullOrEmpty(developProjectSalesSearchDTO.Project))
            .WhereIF(a => a.SaleStaffName.Contains(developProjectSalesSearchDTO.SaleStaffName),
                !string.IsNullOrEmpty(developProjectSalesSearchDTO.SaleStaffName))
            .WhereIF(a => a.SaleStatus == developProjectSalesSearchDTO.SaleStatus,
                developProjectSalesSearchDTO.SaleStatus != null)
            .WhereIF(a => a.CreateTime > developProjectSalesSearchDTO.StartTime,
                developProjectSalesSearchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < developProjectSalesSearchDTO.EndTime,
                developProjectSalesSearchDTO.EndTime != null)
            .Where(a => a.IsDelete == false);

        //返回列表
        var developProjectSales = await query
            .OrderBy(a => a.CreateTime)
            .Page(developProjectSalesSearchDTO.PageIndex, developProjectSalesSearchDTO.PageSize)
            .ToListAsync();

        //总数据量
        var pageCount = await query.CountAsync();

        //返回数据
        var pageResult = new PageResult<DevelopProjectSalesView>(developProjectSales, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 新增开发管理项目销售

    public async Task<RequestResponseModel> AddDevelopProjectSale(DevelopProjectSalesAddDTO developProjectSalesAddDTO)
    {
        //校验员工
        var staff = await Valid.ValidId(_context.Staff, _userContext.UserId);
        if (staff == null) return RequestResponse.BadRequest("员工不存在");
        
        //校验销售人
        var saleStaff = await Valid.ValidId(_context.Staff, developProjectSalesAddDTO.SaleStaffId);
        if (saleStaff == null) return RequestResponse.BadRequest("销售员工不存在");
        
        //生成新数据
        var developProject = _mapper.Map<DevelopProjectManagerModel>(developProjectSalesAddDTO);

        developProject.Id = Guid.NewGuid();
        developProject.CreateStaffId = staff.Id.ToString();
        developProject.CreateStaffName = staff.Name;
        developProject.SaleStaffName = saleStaff.Name;
        developProject.SaleStatus = SaleStatusEnum.潜在客户;
        developProject.DevelopStatus = DevelopStatusEnum.待确认;
        developProject.ImplementStatus = ImplementStatusEnum.待实施;
        developProject.IsDelete = false;
        developProject.CreateTime = DateTime.Now;

        //新增数据
        _context.DevelopProjectManager.Add(developProject);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(developProject.Id, "新增成功");
    }

    #endregion

    #region 更新开发管理项目销售

    public async Task<RequestResponseModel> PutDevelopProjectSale(
        DevelopProjectSalesUpdateDTO developProjectSalesUpadteDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, developProjectSalesUpadteDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");

        //编辑数据
        var developProject = _mapper.Map(developProjectSalesUpadteDTO, query);

        //更新表
        _context.DevelopProjectManager.Update(developProject);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(developProjectSalesUpadteDTO.Id);
    }

    #endregion

    #region 删除开发管理项目销售

    public async Task<RequestResponseModel> DeleteDevelopProjectSale(SingleIdDTO singleIdDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, singleIdDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        query.IsDelete = true;

        //删除操作
        _context.DevelopProjectManager.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(singleIdDTO.Id, "删除成功");
    }

    #endregion

    #region 批量删除开发管理项目销售

    public async Task<RequestResponseModel> DeleteArrayDevelopProjectSale(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectManager
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        foreach (var item in query) item.IsDelete = true;
        ;

        //删除并保存
        _context.DevelopProjectManager.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "删除成功");
    }

    #endregion

    #region 开发管理项目销售 - 沟通中

    public async Task<RequestResponseModel> CommunicateArrayDevelopProjectSale(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectManager
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.All(a => a.SaleStatus != SaleStatusEnum.潜在客户)) return RequestResponse.BadRequest("必须是潜在客户才能沟通");

        foreach (var item in query) item.SaleStatus = SaleStatusEnum.沟通中;
        ;

        //更新并保存
        _context.DevelopProjectManager.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "状态成功设置更新为[沟通中]");
    }

    #endregion

    #region 开发管理项目销售 - 项目金额

    public async Task<RequestResponseModel> AmountDevelopProjectSale(
        DevelopProjectSalesAmountDTO developProjectSalesAmountDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, developProjectSalesAmountDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.SaleStatus != SaleStatusEnum.沟通中 && query.SaleStatus != SaleStatusEnum.待付款 &&
            query.SaleStatus != SaleStatusEnum.已下定) return RequestResponse.BadRequest("只有[沟通中]，[待付款]和[已下定]状态才能修改项目金额");

        query.TotalAmount = developProjectSalesAmountDTO.TotalAmount;
        query.SaleStatus = SaleStatusEnum.待付款;

        //更新操作
        _context.DevelopProjectManager.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(developProjectSalesAmountDTO.Id, "项目金额设置成功");
    }

    #endregion

    #region 开发管理项目销售 - 下定项目

    public async Task<RequestResponseModel> DepositAmountDevelopProjectSale(
        DevelopProjectSalesPayAmountDTO developProjectSalesPayAmountDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, developProjectSalesPayAmountDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.SaleStatus != SaleStatusEnum.待付款) return RequestResponse.BadRequest("只有[待付款]状态才能下定项目");

        query.PayAmount = developProjectSalesPayAmountDTO.PayAmount;
        query.SaleStatus = SaleStatusEnum.已下定;

        //更新操作
        _context.DevelopProjectManager.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(developProjectSalesPayAmountDTO.Id, "项目下定成功");
    }

    #endregion

    #region 开发管理项目销售 - 付款

    public async Task<RequestResponseModel> PayAmountDevelopProjectSale(
        DevelopProjectSalesPayAmountDTO developProjectSalesPayAmountDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, developProjectSalesPayAmountDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.SaleStatus != SaleStatusEnum.已下定) return RequestResponse.BadRequest("只有[已下定]状态才能付款");

        query.PayAmount += developProjectSalesPayAmountDTO.PayAmount;

        //更新操作
        _context.DevelopProjectManager.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(developProjectSalesPayAmountDTO.Id, "项目付款成功");
    }

    #endregion

    #region 开发管理项目销售 - 完成

    public async Task<RequestResponseModel> FinishArrayDevelopProjectSale(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectManager
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.Any(a => a.SaleStatus == SaleStatusEnum.已完成 || a.SaleStatus == SaleStatusEnum.已取消))
            return RequestResponse.BadRequest("已完成或者已取消的项目不能完成");

        foreach (var item in query) item.SaleStatus = SaleStatusEnum.已完成;
        ;

        //更新并保存
        _context.DevelopProjectManager.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "项目完成成功");
    }

    #endregion

    #region 开发管理项目销售 - 取消

    public async Task<RequestResponseModel> CancelArrayDevelopProjectSale(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectManager
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.Any(a => a.SaleStatus == SaleStatusEnum.已完成 || a.SaleStatus == SaleStatusEnum.已取消))
            return RequestResponse.BadRequest("已完成或者已取消的项目不能取消");

        foreach (var item in query) item.SaleStatus = SaleStatusEnum.已取消;
        ;

        //更新并保存
        _context.DevelopProjectManager.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "项目取消成功");
    }

    #endregion
}